package com.itheima.service.store.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.store.CourseDao;
import com.itheima.domain.store.Course;
import com.itheima.factory.MapperFactory;
import com.itheima.service.store.CourseService;
import com.itheima.utils.TransactionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class CourseServiceImpl implements CourseService {
    @Override
    public int save(Course course) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        int rst = mapper.save(course);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public int delete(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        int rst = mapper.delete(id);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public int update(Course course) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        int rst = mapper.update(course);
        TransactionUtil.commit(sqlSession);
        this.findAll();
        TransactionUtil.close(sqlSession);
        return rst;
    }

    @Override
    public Course findById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        Course course = mapper.findById(id);

        this.findAll();
        TransactionUtil.close(sqlSession);
        return course;
    }

    @Override
    public List<Course> findAll() {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        List<Course> all = mapper.findAll();
        TransactionUtil.close(sqlSession);
        return all;
    }

    @Override
    public PageInfo findAll(int currentPage, int pageSize) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        CourseDao mapper = MapperFactory.getMapper(sqlSession, CourseDao.class);
        PageHelper.startPage(currentPage, pageSize);
        List<Course> all = mapper.findAll();

       PageInfo pageInfo = new PageInfo(all);
        TransactionUtil.close(sqlSession);
        return pageInfo;
    }
}
